<template>
  <div class="customer-list-container">
    <!-- 搜索区域 -->
    <div class="filter-section">
      <el-form :model="filterForm" inline>
        <el-form-item label="姓名">
          <el-input v-model="filterForm.name" placeholder="请输入姓名" clearable style="width: 90px" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="filterForm.phone" placeholder="请输入手机号" clearable style="width: 120px" />
        </el-form-item>
        <el-form-item label="公司">
          <el-input v-model="filterForm.company" placeholder="请输入公司名称" clearable style="width: 120px" />
        </el-form-item>
        <el-form-item label="营业执照">
          <el-select v-model="filterForm.hasLicense" placeholder="请选择" clearable style="width: 130px">
            <el-option label="全部" :value="null" />
            <el-option label="有营业执照" :value="true" />
            <el-option label="无营业执照" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleFilter">搜索</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 客户列表 -->
    <div class="table-section">
      <el-table :data="customerList" v-loading="loading" style="width: 100%" height="calc(100vh - 250px)" stripe>
        <el-table-column prop="cid" label="客户ID" width="100" align="center" />
        <el-table-column prop="name" label="姓名" width="120" />
        <el-table-column prop="phone" label="手机号" width="150" />
        <el-table-column prop="company" label="公司" width="200" show-overflow-tooltip />
        <el-table-column prop="address" label="地址" width="250" show-overflow-tooltip />
        <!-- 新增的三个字段 -->
        <!-- <el-table-column prop="active_count" label="订单数" width="120" align="center" />
        <el-table-column prop="cce" label="消费金额" width="150" align="right">
          <template #default="{ row }">
            ¥{{ formatMoney(row.cce)  }}
          </template>
        </el-table-column>
        <el-table-column prop="cpq" label="产品销量" width="120" align="center" /> -->

        <el-table-column prop="active_count" label="订单数" width="120" align="center">
          <template #header>
            <span style="display: flex; align-items: center; justify-content: center;">
              <el-icon style="margin-right: 5px;">
                <List />
              </el-icon>
              <span>订单数</span>
            </span>
          </template>
          <template #default="{ row }">
            <el-tag :type="row.active_count > 10 ? 'success' : row.active_count > 5 ? 'warning' : 'info'" size="small">
              {{ row.active_count }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="cce" label="消费金额" width="150" align="right">
          <template #header>
            <span style="display: flex; align-items: center; justify-content: flex-end;">
              <el-icon style="margin-right: 5px;">
                <Money />
              </el-icon>
              <span>消费金额</span>
            </span>
          </template>
          <template #default="{ row }">
            <span style="font-weight: 600; color: #e6a23c;">
              ¥{{ formatMoney(row.cce) }}
            </span>
          </template>
        </el-table-column>

        <el-table-column prop="cpq" label="产品销量" width="120" align="center">
          <template #default="{ row }">
            <span style="font-weight: bold">{{ row.cpq }}</span>
          </template>
        </el-table-column>

        <!-- 原有字段 -->
        <el-table-column prop="registerdate" label="注册日期" width="180" align="center">
          <template #default="{ row }">
            {{ formatDate(row.register_date) }}
          </template>
        </el-table-column>
        <el-table-column label="营业执照" width="120" align="center">
          <template #default="{ row }">
            <el-button v-if="row.license_image" type="text" size="small" @click="viewLicense(row.license_image)">
              查看
            </el-button>
            <span v-else>-</span>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页控制 -->
    <div class="pagination-section">
      <el-button :disabled="!hasPrevPage || loading" @click="loadPrevPage" v-if="hasPrevPage">
        ← 上一页
      </el-button>

      <el-button :disabled="!hasNextPage || loading" @click="loadNextPage" :loading="loading">
        {{ loading ? '加载中...' : '下一页 →' }}
      </el-button>

      <span class="page-info" v-if="customerList.length > 0">
        当前显示 {{ customerList.length }} 条记录
        <span v-if="!hasNextPage">- 已加载全部</span>
      </span>
    </div>

    <!-- 图片预览对话框 -->
    <el-dialog v-model="imagePreviewVisible" title="营业执照" width="60%">
      <div style="text-align: center;">
        <img :src="currentImage" style="max-width: 100%; max-height: 500px;" />
      </div>
    </el-dialog>
  </div>
</template>
 
<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { customer_ListWithFiltersAPI } from '@/api/api'

// 图片预览 
const imagePreviewVisible = ref(false)
const currentImage = ref('')

// 过滤表单 
const filterForm = reactive({
  name: '',
  phone: '',
  company: '',
  hasLicense: null
})

// 响应式数据 
const loading = ref(false)
const customerList = ref([])
const nextCursor = ref(null)
const cursorStack = ref([])
const hasNextPage = ref(true)
const hasPrevPage = ref(false)

// 处理分页响应 
const handlePageResponse = (data) => {
  customerList.value = data.data
  nextCursor.value = data.nextCursor
  hasNextPage.value = data.hasNext
  hasPrevPage.value = cursorStack.value.length > 0
}

// 构建请求参数 
const buildParams = (cursor = null) => {
  return {
    cursor: cursor,
    limit: 10,
    name: filterForm.name,
    phone: filterForm.phone,
    company: filterForm.company,
    hasLicense: filterForm.hasLicense
  }
}

// 加载数据（带过滤条件）
const loadData = async (cursor = null) => {
  loading.value = true
  try {
    const params = buildParams(cursor)
    const response = await customer_ListWithFiltersAPI(params)

    if (response.code === 200) {
      handlePageResponse(response.data)
      ElMessage.success(' 数据加载成功')
    }
  } catch (error) {
    ElMessage.error(' 数据加载失败：' + error.message)
  } finally {
    loading.value = false
  }
}

// 加载第一页 
const loadFirstPage = async () => {
  cursorStack.value = []
  await loadData(null)
}

// 加载下一页 
const loadNextPage = async () => {
  if (!nextCursor.value || loading.value) return

  loading.value = true
  try {
    // 将当前游标存入历史栈 
    if (nextCursor.value) {
      cursorStack.value.push(nextCursor.value)
    }

    const params = buildParams(nextCursor.value)
    const response = await customer_ListWithFiltersAPI(params)

    if (response.code === 200) {
      handlePageResponse(response.data)
      ElMessage.success(' 下一页数据加载成功')
    }
  } catch (error) {
    ElMessage.error(' 加载下一页失败：' + error.message)
  } finally {
    loading.value = false
  }
}

// 加载上一页 
const loadPrevPage = async () => {
  if (cursorStack.value.length <= 1) {
    // 如果是第一页的前一页，就回到第一页 
    await loadFirstPage()
    return
  }

  loading.value = true
  try {
    // 弹出当前页的游标，获取上一页的游标 
    cursorStack.value.pop()  // 移除当前页 
    const prevCursor = cursorStack.value[cursorStack.value.length - 1] || null

    const params = buildParams(prevCursor)
    const response = await customer_ListWithFiltersAPI(params)

    if (response.code === 200) {
      handlePageResponse(response.data)
      ElMessage.success(' 上一页数据加载成功')
    }
  } catch (error) {
    ElMessage.error(' 加载上一页失败：' + error.message)
  } finally {
    loading.value = false
  }
}

// 过滤搜索 
const handleFilter = async () => {
  await loadFirstPage()
}

// 重置过滤 
const resetFilter = () => {
  filterForm.name = ''
  filterForm.phone = ''
  filterForm.company = ''
  filterForm.hasLicense = null
  loadFirstPage()
}

// 查看营业执照 
const viewLicense = (imageUrl) => {
  currentImage.value = imageUrl
  imagePreviewVisible.value = true
}

// 日期格式化 
const formatDate = (dateString) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleDateString('zh-CN')
}

// 金额格式化（新增）
const formatMoney = (value) => {
  if (value === null || value === undefined) return '0.00'
  return Number(value).toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })
}

// 初始化加载 
onMounted(() => {
  loadFirstPage()
})
</script>
 
<style scoped>
.customer-list-container {
  padding: 20px;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f7fa;
}

.filter-section {
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.table-section {
  flex: 1;
  margin-bottom: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.pagination-section {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 15px 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.page-info {
  color: #606266;
  font-size: 14px;
  margin-left: auto;
}
</style>